package com.jdk.demo.asynchronousFileChannel.获取给定区域独占锁;

import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

// 获取通道文件给定区域的锁
public class Test1 {

	public static void main(String[] args) throws Exception {
		Path path = Paths.get("E:/zsl/temp2.txt");
		AsynchronousFileChannel channel =  AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
		Future<FileLock> future = channel.lock(0, 3, false);
		FileLock lock = future.get();
		System.out.println("A get lock time=" + System.currentTimeMillis());
		Thread.sleep(8000); // 给出一些时间，用来启动test2
		lock.release();
		System.out.println("A release lock time=" + System.currentTimeMillis());
		channel.close();
	}

}
